// var MongoClient = require('mongodb').MongoClient;
// var url = 'mongodb://localhost:27017/range';
// var collection = MongoClient.connect(url, {useNewUrlParser: true});
//这个应该写在一个文件里面
var fs = require("fs");
var configLib = require("../config.lib");
var newsModel = require("../models/news.model");


module.exports = {
    getList:function(req, res, next){
        let filter = { deleted: false };
        if(req.query.searchTitle){
            filter.title = {$regex : new RegExp(req.query.searchTitle), $options:"$i"};
        }
        if(req.query.searchAuthor){
            filter.author = {$regex : new RegExp(req.query.searchAuthor), $options:"$i"};
        }
        newsModel.find(filter, function(err, data){
            res.json({
                success:true,
                data:data
            })
        })
    },
    addItem:function(req, res, next){
        //添加新闻内容
        let body = req.body;
        let values = JSON.parse(body.values);
        let filename = './dist' + configLib.newsPathFormat + values.title + "-" + values.author + "-" + values.contentName +'.txt';
        let obj = {...JSON.parse(body.values),
            cover: configLib.imageUrlPrefix + req.file.path.replace(/^dist\\/, '').replace(/\\/g, '/'),//封面位置
            content: filename,//内容位置
        };
        delete obj.contentName;
        delete obj.__v;
        let news = new newsModel({...obj, date: Date.now()});

        news.save((err, data)=>{
            if(err){
                console.log(err);
                res.json({
                    success:false,
                    description:"保存文章出错"
                })
            }else{
                res.json({
                    success:true,
                    data:{
                        "state": "SUCCESS",
                        "url": configLib.imageUrlPrefix + req.file.path.replace(/^dist\\/, '').replace(/\\/g, '/'),
                        "title": req.file.filename,
                        "original": req.file.filename,
                        "desc":"newArticle返回的结果",
                    }
                })
            }
        })
    },
    getItem:function(req, res, next){
        if(req.query){
            newsModel.find({_id: req.query.id},function(err, data){
                data = data[0];
                fs.readFile(data.content , function(err, nowdata) {
                    if(err){
                        console.error("读取文件失败");
                    }else{
                        data.content = nowdata;
                        res.json({
                            success:true,
                            data: data
                        })
                    }
                });
            })
        }
    },
    deleteItems:function(req, res, next){
        let body = JSON.parse(req.body.data);
        let ids = body.ids,
            flag = true;
        console.log("删除的ids", ids);
        if(Array.isArray(ids)){//删除多个,好像要用递归？？？
            for(let i = 0; i < ids.length; i++){
                if(!flag)break;
                newsModel.updateOne({"_id":ids[i]}, {"deleted": true}, function(err, data){
                    if(err){
                        console.log(err);
                        flag = false;
                    }
                })
            }
            if(flag){
                res.json({
                    success: true,
                    data:{ description:"数据一条数据完成" }
                });
            }else{
                res.json({
                    success: false,
                    data:{ description:"数据没有删除完" }
                })
            }
        }else{//删除一个
            newsModel.updateOne({"_id":ids},{ $set: {"deleted": true}}, function(err, data){
                if(err){
                    console.log(err);
                    res.json({
                        success: false,
                        data:{ description:"删除失败" }
                    })
                }else{
                    res.json({
                        success: true,
                        data:{ description:"删除一条数据完成" }
                    });
                }
            })
        }
    },
    updateItem:function(req, res, next){
        //更新数据 content
        let body = req.body;
        let values = JSON.parse(req.body.values);

        if(body.id){
            let filename = "", filenamearr = [], realName = [];
            newsModel.find({_id: body.id},function(err, data){
                if(data){
                    data = data[0];
                    filename = data.content;
                    filenamearr = filename.split("/"),
                    realName = filenamearr[filenamearr.length - 1].split("-");
                    realName[0] = values.title;
                    realName[1] = values.author;
                    filenamearr[filenamearr.length - 1] = realName.join("-");
                    filename = filenamearr.join("/");
                    newsModel.findByIdAndUpdate(body.id, {...values, content: filename}, function(err, data){
                        if(err){
                            console.err(err);
                            res.json({
                                success:false,
                                description:"更新数据失败，错误",
                                data:{ err:err }
                            })
                        }else{
                            console.log("data", data);
                            res.json({
                                success:true,
                                data:{ data:data }
                            })
                        }
                    })
                }else{
                    res.json({
                        success:false,
                        description:"更新的时候找不到数据",
                        data:{}
                    })
                }
            })
            
        }
    }
}
